package com.lagou.edu.dao.impl;

import com.lagou.edu.annotation.Autowired;
import com.lagou.edu.annotation.Repository;
import com.lagou.edu.dao.IAccountDao;
import com.lagou.edu.pojo.Account;
import com.lagou.edu.transaction.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Kirito
 * @description:
 * @date 2020/04/04
 */
@Repository
public class JdbcAccountDaoImpl implements IAccountDao {

    @Autowired
    private ConnectionUtils connectionUtils;

    @Override
    public Account queryAccountByCardNo(String cardNo) throws SQLException {
        // 获取数据库连接
        //DruidPooledConnection connection = DruidUtils.getInstance().getConnection();

        Connection connection = connectionUtils.getCurrentThreadConnection();

        String sql = "select * from account where cardNo = ?";
        // 预编译sql
        PreparedStatement prepareStatement = connection.prepareStatement(sql);
        // 设置参数
        prepareStatement.setString(1, cardNo);
        // 执行sql，获取结果集
        ResultSet resultSet = prepareStatement.executeQuery();

        // 解析结果集
        Account account = new Account();
        while (resultSet.next()) {
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
            account.setCardNo(resultSet.getString("cardNo"));
        }

        // 释放资源
        resultSet.close();
        prepareStatement.close();
        //connection.close();

        return account;
    }

    @Override
    public int updateAccountByCardNo(Account account) throws SQLException{
        Connection connection = connectionUtils.getCurrentThreadConnection();
        String sql = "update account set money = ? where cardNo = ?";
        PreparedStatement prepareStatement = connection.prepareStatement(sql);
        prepareStatement.setInt(1, account.getMoney());
        prepareStatement.setString(2, account.getCardNo());
        int result = prepareStatement.executeUpdate();

        prepareStatement.close();
        //connection.close();

        return result;
    }
}
